/*
 * Copyright (C) 2003-2009 eXo Platform SAS.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.reflext.jlr;

import org.reflext.spi.model.AnnotationModel;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * @author <a href="mailto:julien.viet@exoplatform.com">Julien Viet</a>
 * @version $Revision$
 */
public abstract class JavaLangReflectAnnotationModel<E> implements AnnotationModel<Type, E, Annotation, Method> {

  public Collection<Method> getAnnotationParameters(Annotation annotation) {
    Method[] methods = annotation.annotationType().getDeclaredMethods();
    ArrayList<Method> list = new ArrayList<Method>(methods.length);
    for (Method m : methods) {
      list.add(m);
    }
    return list;
  }

  public Type getAnnotationType(Annotation annotation) {
    return annotation.annotationType();
  }

  public String getAnnotationParameterName(Method parameter) {
    return parameter.getName();
  }

  public Type getAnnotationParameterType(Method parameter) {
    return parameter.getGenericReturnType();
  }

  public List<?> getAnnotationParameterValue(Annotation annotation, Method parameter) {
    try {
      Object value = parameter.invoke(annotation);
      if (value.getClass().isArray()) {
        Object[] array = (Object[])value;
        for (int i = 0;i < array.length;i++) {
          array[i] = unwrap(array[i]);
        }
        return Arrays.asList(array);
      } else {
        return Arrays.asList(unwrap(value));
      }
    }
    catch (Exception e) {
      throw new AssertionError(e);
    }
  }

  private Object unwrap(Object o) {
    if (o instanceof Enum) {
      return ((Enum)o).name();
    } else {
      return o;
    }
  }
}
